import subprocess
from time import sleep

from appium import webdriver
from appium.options.common.base import AppiumOptions
from appium.webdriver.common.appiumby import AppiumBy

options = AppiumOptions()
options.load_capabilities({
	"platformName": "Android",
	"appium:automationName": "UiAutomator2",
	"appium:ensureWebviewsHavePages": True,
	"appium:nativeWebScreenshot": True,
	"appium:newCommandTimeout": 3600,
	"appium:noReset": True,
	"appium:connectHardwareKeyboard": True,
	"appium:appPackage": "com.xiaomi.shop",
	"appium:appActivity": ".activity.MainTabActivity "
})

driver = webdriver.Remote("http://127.0.0.1:4723", options=options)
driver.implicitly_wait(10)

el1 = driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value="new UiSelector().text(\"小米上新\")")
el1.click()
el2 = driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value="new UiSelector().className(\"android.view.ViewGroup\").instance(29)")
el2.click()
el3 = driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value="new UiSelector().className(\"android.widget.ImageView\").instance(6)")
el3.click()
el4 = driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value="new UiSelector().text(\"去购买\").instance(2)")
el4.click()
el5 = driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value="new UiSelector().resourceId(\"com.xiaomi.shop.plugin.rank:id/detail_product_buy_tv\").instance(0)")
el5.click()
el6 = driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value="new UiSelector().text(\"加入购物车\")")
el6.click()
el7 = driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR, value="new UiSelector().text(\"加入购物车\")")
el7.click()
el8 = driver.find_element(by=AppiumBy.XPATH, value="//android.widget.TextView[@text=\"购物车\"]")
el8.click()

driver.quit()



class PageShoppingNew:
    def __init__(self):
        start_appium = f"appium -a 127.0.0.1 -p {4723} --session-override"
        process = subprocess.Popen(
            start_appium,
            shell=True,
            stdout=True,
            stderr=subprocess.STDOUT,
        )

        options = AppiumOptions()
        options.load_capabilities({
            "platformName": "Android",
            "appium:automationName": "UiAutomator2",
            "appium:ensureWebviewsHavePages": True,
            "appium:nativeWebScreenshot": True,
            "appium:newCommandTimeout": 3600,
            "appium:noReset": True,
            "appium:connectHardwareKeyboard": True,
            "appium:appPackage": "com.xiaomi.shop",
            "appium:appActivity": ".activity.MainTabActivity "
        })

        self.driver = webdriver.Remote("http://127.0.0.1:4723", options=options)
        self.driver.implicitly_wait(10)

        def goto_shopping_cart(self):
            pass